<template>
  <div>
    <el-radio-group v-model="state.type" class="claim-btn" size="large" @change="bindTypeChange">
      <el-radio-button label="全部" value="" />
      <el-radio-button label="待审核" value="dsp" />
      <el-radio-button label="待付款或待提交" value="xd" />
      <el-radio-button label="待自提" value="dhx" />
      <el-radio-button label="待发货" value="fk" />
      <el-radio-button label="部分发货" value="bfck" />
      <el-radio-button label="待收货" value="ck" />
      <el-radio-button label="已完成" value="wc" />
      <el-radio-button label="已核销" value="yhx" />
      <el-radio-button label="已驳回" value="ybh" />
    </el-radio-group>
    <div class="search">
      <el-input v-model="state.search" style="max-width: 30%" placeholder="商品或订单号搜索" @keyup.enter="handleSearch">
        <template #append>
          <el-button :icon="Search" @click.prevent="handleSearch" class="order-search" />
        </template>
      </el-input>
    </div>
    <div>
      <el-row :gutter="10" class="list-header">
        <el-col :span="10">
          <div class="item-th" style="text-align: left;padding-left: 30px;">商品</div>
        </el-col>
        <el-col :span="2">
          <div class="item-th">商品种类</div>
        </el-col>
        <el-col :span="3">
          <div class="item-th">订单金额</div>
        </el-col>
        <el-col :span="2">
          <div class="item-th">收货人</div>
        </el-col>
        <el-col :span="2">
          <div class="item-th">状态</div>
        </el-col>
        <el-col :span="2">
          <div class="item-th">订单来源</div>
        </el-col>
        <el-col :span="3">
          <div class="item-th">操作</div>
        </el-col>
      </el-row>
    </div>
    <div class="order-box" v-loading="other.loading">
      <template v-if="other.dataList.length">
        <div v-for="order in other.dataList" :key="order.id" class="order">
          <div class="order-header">
            <div class="order-info">
              <div class="order-shop__img"><el-avatar shape="square" :size="22" :src="order.shopVo.pic || ''" /></div>
              <div class="order-shop__title">{{ order.shopVo.name }}</div>
              <div class="order-time">{{ $timeDisplay('', '', order.ctime) }}</div>
              <div class="order-number">订单号：{{ order.orderCode }}</div>
            </div>
          </div>
          <el-row :gutter="10" class="order-body" align="middle">
            <el-col :span="10">
              <div class="item-td goods-list" style="text-align: left;">
                <div v-for="goods in order.viewSellVos" :key="goods.id" class="goods-info">
                  <el-image style="width: 128px; height: 128px; background-color: #fff;" :src="goods.img" fit="cover" />
                  <div class="goods-other">
                    <div>{{ $numberPriceDisplay(goods.computedprice) }}</div>
                    <div>{{ goods.count }}</div>
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="2">
              <div class="item-td">{{ order.sellVos.length }}</div>
            </el-col>
            <el-col :span="3">
              <div class="item-td">{{ $numberPriceDisplay(order.totalPrice) }}</div>
            </el-col>
            <el-col :span="2">
              <div class="item-td">{{ order.consignorName || '-' }}</div>
            </el-col>
            <el-col :span="2">
              <div class="item-td">
                <div>{{ order.stateDisplay }}</div>
                <div style="color: var(--jbc-color)" v-if="order.state === 'ybh' && order.approveRemarks">{{
                  order.approveRemarks }}</div>
                <div style="color: var(--jbc-color)" v-if="order.refundId && order.refundInfoVo.status === 'N'">拒退备注：{{
                  order.refundInfoVo.response }}</div>
              </div>
            </el-col>
            <el-col :span="2">
              <div class="item-td">{{ order.typeDisplay }}</div>
            </el-col>
            <el-col :span="3">
              <div class="item-td td-opt">
                <!-- 订单为可以付款 -->
                <el-button v-if="order.isPay === 'Y'" class="link-button" color="#D6000F"
                  @click="handleCommand('pay', order)" plain>{{ order.shopVo?.type === '2' ? '去提交' : '去付款'
                  }}</el-button>
                <!-- 非零售订单 -->
                <el-button v-if="order.isShar === 'Y'" class="link-button" color="#D6000F"
                  @click="handleCommand('share', order)" plain>分享订单模版</el-button>
                <!-- 订单为已发货 -->
                <el-button v-if="order.isOver === 'Y'" class="link-button" color="#D6000F"
                  @click="handleCommand('confirm', order)" plain>确认收货</el-button>
                <!-- 订单为部分发货 -->
                <!-- <el-button v-if="order.state === 'bfck'" class="link-button" color="#D6000F"
                  @click="handleCommand('confirmPart', order)" plain>确认收货</el-button> -->
                <!-- 订单为自提 -->
                <el-button v-if="order.isCheck === 'Y'" class="link-button" color="#D6000F"
                  @click="handleCommand('showCode', order)" plain>自提核销码</el-button>
                <!-- 订单为可以取消 -->
                <el-button v-if="order.isQx === 'Y'" class="link-button" @click="handleCommand('cancel', order)"
                  plain>取消订单</el-button>
                <!-- 订单可以申请退款 -->
                <el-button v-if="order.isRefund === 'Y'" class="link-button" color="#D6000F"
                  @click="handleCommand('refund', order)" plain>申请售后</el-button>
                <el-button class="link-button" @click="handleCommand('detail', order)" plain>查看详情</el-button>
              </div>
            </el-col>
          </el-row>
        </div>
      </template>
      <el-empty v-else-if="!other.dataList.length && !other.loading"
        :description="`暂无${orderStateMap[state.type] || ''}订单`" />
    </div>
    <el-pagination v-show="other.dataList.length" class="pagination" v-model:current-page="state.pageNum"
      :page-size="state.pageSize" layout="total, prev, pager, next" :total="other.total"
      @current-change="handleCurrentChange" />
    <refundForm ref="dataFormRef" @change="bindChangeList"></refundForm>
    <confirmForm ref="dataConfirmFormRef" @change="bindChangeList"></confirmForm>
  </div>
</template>

<script setup name="order">
import { appOrderMyOrderListGet, appOrderQxGet, appOrderOverPost } from '@/api/order'
import useClipboard from 'vue-clipboard3'
import { dialogCustomStyle } from '@/components/webCustom/utils'
import { orderStateMap, orderTypeMap, orderPayTypeMap } from './components/orderHelp'
import { Search } from '@element-plus/icons-vue'
import refundForm from './components/refundForm'
import confirmForm from './components/confirmForm'

const { proxy } = getCurrentInstance()
const router = useRouter()
const dataFormRef = ref(null)
const dataConfirmFormRef = ref(null)
const state = reactive({
  search: '',
  type: '',
  pageNum: 1,
  pageSize: 10
})
const other = reactive({
  dataList: [],
  total: 0,
  loading: false,
  noMore: false
})
function getList () {
  other.loading = true;
  appOrderMyOrderListGet({ params: state }).then((res) => {
    if (res.code === 0) {
      const total = parseInt(res.data.total)
      res.data.records.forEach(it => {
        it.stateDisplay = it.state === 'xd' && it.shopVo.type === '2' ? '待提交' : orderStateMap[it.state]
        it.typeDisplay = orderTypeMap[it.type]
        it.payTypeDisplay = orderPayTypeMap[it.payType]
        it.to = { name: 'orderDetail', params: { id: it.id } }
        it.payTo = { name: 'orderPayment', params: { id: it.id } }
        it.viewSellVos = it.sellVos.slice(0, 6)
      })
      other.dataList = res.data.records;
      other.total = total;
      other.noMore = total <= state.pageSize * state.pageNum
    } else {
      other.$message({ message: res.msg, type: 'error' });
    }
  }).finally(() => {
    console.log('end')
    other.loading = false
  });
}
getList()
function bindTypeChange (v) {
  state.type = v
  state.pageNum = 1
  getList()
}
const handleCurrentChange = (val) => {
  state.pageNum = val
  getList()
}
function handleSearch () {
  state.pageNum = 1
  getList()
}
const bindChangeList = (v) => {
  getList()
}

const { toClipboard } = useClipboard()
function handleCommand (command, r) {
  switch (command) {
    case 'pay': // 去付款
      router.push(r.payTo)
      break
    case 'share': // 分享订单模版
      const link = `${location.origin}/${import.meta.env.VITE_APP_HISTORY === 'history' ? '' : '#/'}share/${r.id}`
      proxy.$modal.confirm(
        `<div style="font-weight: bold;font-size: 16px;color: #323232;line-height: 21px;">订单模板分享链接</div><div style="background-color: #F5F6F5;font-size: 16px;color: #323232;line-height: 21px;padding: 12px 18px;margin-top: 14px;">${link}</div>`,
        { title: "分享订单模板链接", type: '' },
        {
          dangerouslyUseHTMLString: true,
          draggable: true,
          customClass: 'custom-message-box',
          customStyle: dialogCustomStyle({ width: '572px' }),
          showClose: false,
          confirmButtonText: '复制链接',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confirmButtonText = '复制中...'
              toClipboard(link).then(flag => {
                console.log(flag)
                proxy.$modal.msgSuccess(`链接已复制成功`)
                done()
                setTimeout(() => {
                  instance.confirmButtonLoading = false
                }, 300)
              }).catch(e => {
                console.log(e)
                proxy.$modal.msgError('链接已复制失败，请手动复制')
                instance.confirmButtonLoading = false
              })
            } else {
              done()
            }
          }
        }
      ).catch((err) => { console.log(err) })
      break
    case 'confirm': // 确认收货
      // dataConfirmFormRef.value.show()
      // dataConfirmFormRef.value.$nextTick(() => {
      //   dataConfirmFormRef.value.setDefault({ id: r.id }, r)
      // })
      
      proxy.$modal.confirm('<div style="display: flex;flex-direction: column;word-break: break-all;align-items: center;font-weight: bold;font-size: 18px;color: #323232;line-height: 21px; text-algin">您确定要对编号【' + r.orderCode + '】订单进行【确认收货】操作吗？</div>', { title: '温馨提示' }, {
        type: '',
        dangerouslyUseHTMLString: true,
        draggable: true,
        customClass: 'custom-message-box',
        customStyle: dialogCustomStyle({ width: '385px' }),
        showClose: false,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '确认中...'
            appOrderOverPost({ body: { id: r.id } }).then((res) => {
              if (res.code === 0) {
                proxy.$modal.msgSuccess("确认成功！");
                done()
                getList()
              } else {
                proxy.$modal.msgError(res.msg);
              }
            }).finally(() => {
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      }).then(action => {
        console.log('confirm', action)
      }).catch(action => {
        console.log('cancel', action)
      })
      break
    case 'confirmPart': // 确认收货(部分发货)
      // TODO 确认收货(部分发货) 暂时不做处理
      break
    case 'showCode': // 自提二维码
      const checkCode = r.checkCode
      proxy.$modal.confirm(`<div style="display: flex;flex-direction: column;align-items: center;font-weight: bold;font-size: 40px;color: #323232;line-height: 21px; text-algin">${checkCode}</div>`,
        { title: '自提核销码' },
        {
          type: '',
          confirmButtonText: '复制',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          draggable: true,
          customClass: 'custom-message-box',
          customStyle: dialogCustomStyle({ width: '385px' }),
          showClose: false,
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confirmButtonText = '复制中...'
              toClipboard(checkCode).then(flag => {
                console.log(flag)
                proxy.$modal.msgSuccess(`自提核销码已复制成功`)
                done()
                setTimeout(() => {
                  instance.confirmButtonLoading = false
                }, 300)
              }).catch(e => {
                console.log(e)
                proxy.$modal.msgError('自提核销码复制失败，请手动复制')
                instance.confirmButtonLoading = false
              })
            } else {
              done()
            }
          }
        }).then(action => {
          console.log('confirm', action)
        }).catch(action => {
          console.log('cancel', action)
        })
      break
    case 'cancel': // 取消订单
      proxy.$modal.confirm('<div style="display: flex;flex-direction: column;word-break: break-all;align-items: center;font-weight: bold;font-size: 18px;color: #323232;line-height: 21px; text-algin">您确定要对编号【' + r.orderCode + '】订单进行取消操作吗？</div>', { title: '温馨提示' }, {
        type: '',
        dangerouslyUseHTMLString: true,
        draggable: true,
        customClass: 'custom-message-box',
        customStyle: dialogCustomStyle({ width: '385px' }),
        showClose: false,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '取消中...'
            appOrderQxGet({ params: { id: r.id } }).then((res) => {
              if (res.code === 0) {
                proxy.$modal.msgSuccess("取消成功！");
                done()
                getList()
              } else {
                proxy.$modal.msgError(res.msg);
              }
            }).finally(() => {
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      }).then(action => {
        console.log('confirm', action)
      }).catch(action => {
        console.log('cancel', action)
      })
      break
    case 'refund': // 申请退款
      dataFormRef.value.show()
      dataFormRef.value.$nextTick(() => {
        const { id, totalPrice, refundId, refundInfoVo } = r
        dataFormRef.value.setDefault(!refundId || (refundInfoVo && refundInfoVo.status === 'N')  ? { id, applyAmount: totalPrice } : {
          id,
          rid: refundId,
          applyAmount: totalPrice,
          description: refundInfoVo ? refundInfoVo.description : '',
          evidence: refundInfoVo ? refundInfoVo.evidence : '',
          reason: refundInfoVo ? refundInfoVo.reason : '',
          skuTitle: refundInfoVo ? (refundInfoVo.skuTitle || '') : '',
          skuNo: refundInfoVo ? (refundInfoVo.skuNo || '') : '',
          skuCout: refundInfoVo ? (refundInfoVo.skuCout || '') : ''
        }, r)
      })
      break
    case 'detail': // 查看详情
      router.push(r.to)
      break
    default:
      proxy.$modal.msgSuccess("敬请期待！");
      break;
  }
}
</script>

<style lang="scss" scoped>
.list-header {
  background: #F8F8F8;
  border-radius: 8px;

  .item-th {
    font-weight: bold;
    font-size: var(--jbc-font-size-medium);
    color: var(--jbc-font-color);
    line-height: 22px;
    padding: 16px 0;
    text-align: center;
  }
}

.order {
  margin-top: 10px;

  &-box {
    min-height: 220px;
  }

  &-header {
    margin-left: -5px;
    margin-right: -5px;
    padding: 11px 15px;
    background: #F8F8F8;
    border: 1px solid #EBEBEB;
  }

  &-info {
    display: flex;
    align-items: center;
    font-weight: bold;
    font-size: 14px;
    color: #323232;
    line-height: 19px;
  }

  &-shop__img {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  &-shop__title {
    margin-left: 10px;
  }

  &-time {
    margin-left: 10px;
  }

  &-number {
    margin-left: 10px;
    color: #666666;
  }

  &-body {
    border: 1px solid #EBEBEB;

    .item-td {
      font-size: 18px;
      color: #666666;
      line-height: 24px;
      text-align: center;
      padding: 19px 0;

      &.goods-list {
        padding-left: 14px;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
      }

      .goods-info {
        width: 125px;
        height: 125px;
        background: #FFFFFF;
        border: 1px solid #EBEBEB;
        position: relative;
        margin-left: 10px;

        &:nth-child(3n+1) {
          margin-left: 0;
        }
      }

      .goods-other {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 12px;
        color: #fff;
        background-color: rgba(0, 0, 0, 0.5);
        padding: 0 5px;
        position: absolute;
        z-index: 1;
        left: 0;
        right: 0;
        bottom: 0;
      }

      &.td-opt {
        display: flex;
        flex-direction: column;
      }

      .link-button {
        &~.link-button {
          margin-top: 10px;
          margin-left: 0;
        }
      }
    }
  }
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}

.search {
  margin-left: -4px;
  margin-right: -4px;
  margin-top: 14px;
  margin-bottom: 18px;

  .order-search {
    background-color: var(--jbc-color);
    border-color: var(--jbc-color);
    color: #FFFFFF;
  }
}

:deep(.claim-btn) {
  --el-color-primary: var(--jbc-color);
  --el-button-bg-color: #F8F8F8;
  --el-font-size-base: var(--jbc-font-size-medium);

  margin-left: -4px;
  margin-right: -4px;

  .el-radio-button {
    &__inner {
      padding: 12px 20px;
    }
  }
}
</style>